package com.cbs.java.component.database.sqlite;

import com.cbs.java.component.database.DefaultDatabase;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by brochexu on 8/7/15.
 */
public class SqliteDatabase extends DefaultDatabase {
    private final String Driver = "org.sqlite.JDBC";
    private Connection connection;

    public SqliteDatabase(String fileName) throws ClassNotFoundException, SQLException {
        this(fileName, null);
    }

    public SqliteDatabase(String fileName, OnCreateHandler createHandler) throws ClassNotFoundException, SQLException {
        Class.forName(Driver);

        File file = new File(fileName);
        if (!file.exists()) {
            if (!file.getAbsoluteFile().getParentFile().exists()) {
                file.getAbsoluteFile().getParentFile().mkdirs();
            }

            connection = DriverManager.getConnection("jdbc:sqlite:" + file.getAbsolutePath());
            if (createHandler != null) {
                createHandler.onCreate(this);
            }
        } else {
            connection = DriverManager.getConnection("jdbc:sqlite:" + file.getAbsolutePath());
        }
    }

    @Override
    public Connection getConnection() {
        return connection;
    }
}
